package com.xmtlxx.system.service.impl;

import com.xmtlxx.common.config.XmtlxxConfig;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.exception.ServiceException;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.file.FileUtils;
import com.xmtlxx.common.utils.image.ImageUtils;
import com.xmtlxx.oss.entity.UploadResult;
import com.xmtlxx.oss.factory.OssFactory;
import com.xmtlxx.oss.service.IOssStrategy;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.domain.vo.SysOssVo;
import com.xmtlxx.system.mapper.SysOssMapper;
import com.xmtlxx.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 文件上传 服务层实现
 *
 * @author xmtlxx
 */
@RequiredArgsConstructor
@Service
public class SysOssServiceImpl implements ISysOssService {

    private final SysOssMapper baseMapper;

    @Override
    public TableDataInfo<SysOssVo> queryPageList(SysOssBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOss> lqw = buildQueryWrapper(bo);
        Page<SysOssVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysOss> buildQueryWrapper(SysOssBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOss> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), SysOss::getFileName, bo.getFileName());
        lqw.like(StringUtils.isNotBlank(bo.getOriginalName()), SysOss::getOriginalName, bo.getOriginalName());
        lqw.eq(StringUtils.isNotBlank(bo.getFileSuffix()), SysOss::getFileSuffix, bo.getFileSuffix());
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), SysOss::getUrl, bo.getUrl());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            SysOss::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), SysOss::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getService()), SysOss::getService, bo.getService());
        lqw.eq(StringUtils.isNotBlank(bo.getBuss()), SysOss::getBuss, bo.getBuss());
        lqw.eq(StringUtils.isNotBlank(bo.getObjid()), SysOss::getObjid, bo.getObjid());
        return lqw;
    }

    @Override
    public SysOss getById(Long ossId) {
        return baseMapper.selectById(ossId);
    }

    @Override
    public SysOss upload(MultipartFile file,Map<String,Object> params) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());

        // 文件类型判断
        String checkSuffix = suffix;
        String allows = "jpg/png/jpeg/doc/docx/xls/xls/pdf/ofd";
        checkSuffix = checkSuffix.replaceAll("\\.","").toLowerCase();
        if(!allows.contains(checkSuffix)){//不在允许范围内 抛出异常
            throw new ServiceException("文件类型不允许上传！");
        }

        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType(),params);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }

        // 保存文件信息
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName((StringUtils.isNotEmpty(uploadResult.getBucket())?"/"+uploadResult.getBucket()+"/":"")+uploadResult.getFilename());
        oss.setOriginalName(originalfileName);
        oss.setService(storage.getServiceType().getValue());
        baseMapper.insert(oss);
        //图片类型 生成缩略图
        if(ImageUtils.isImageType(suffix)){
            try {
                //缩略图生成 2023/10/26/643ce0337c3d4fac9cc7035afb52714a.jpeg
                String fileName = uploadResult.getFilename();
                String thumbFileName = "thumbnail_"+fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
                String thumbnailPath = XmtlxxConfig.getFilePath();
                String uploadPath = fileName.substring(0,fileName.lastIndexOf("/"))+"/thumbnail_"+fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
                ImageUtils.saveThumbnail(file,thumbnailPath,thumbFileName);
                File thumbnailFile = new File(thumbnailPath+"/"+thumbFileName);
                MultipartFile thumbnail = FileUtils.fileToMultipartFile(thumbnailFile);
                storage.uploadThumbnail(thumbnail.getBytes(), uploadPath, thumbnail.getContentType(),params);
            } catch (IOException e) {
                throw new ServiceException(e.getMessage());
            }
        }
        return oss;
    }

    @Override
    public SysOss upload(MultipartFile file,Map<String,Object> params,String buss,String objid) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());

        // 文件类型判断
        String checkSuffix = suffix;
        String allows = "jpg/png/jpeg/doc/docx/xls/xls/pdf/ofd/mp4";
        checkSuffix = checkSuffix.replaceAll("\\.","").toLowerCase();
        if(!allows.contains(checkSuffix)){//不在允许范围内 抛出异常
            throw new ServiceException("文件类型不允许上传！");
        }

        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType(),params);
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }

        // 保存文件信息
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName((StringUtils.isNotEmpty(uploadResult.getBucket())?"/"+uploadResult.getBucket()+"/":"")+uploadResult.getFilename());
        oss.setOriginalName(originalfileName);
        oss.setService(storage.getServiceType().getValue());
        oss.setBuss(buss);
        oss.setObjid(objid);
        baseMapper.insert(oss);
        //图片类型 生成缩略图
        if(ImageUtils.isImageType(suffix)){
            try {
                //缩略图生成 2023/10/26/643ce0337c3d4fac9cc7035afb52714a.jpeg
                String fileName = uploadResult.getFilename();
                String thumbFileName = "thumbnail_"+fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
                String thumbnailPath = XmtlxxConfig.getFilePath();
                String uploadPath = fileName.substring(0,fileName.lastIndexOf("/"))+"/thumbnail_"+fileName.substring(fileName.lastIndexOf("/")+1,fileName.length());
                ImageUtils.saveThumbnail(file,thumbnailPath,thumbFileName);
                File thumbnailFile = new File(thumbnailPath+"/"+thumbFileName);
                MultipartFile thumbnail = FileUtils.fileToMultipartFile(thumbnailFile);
                storage.uploadThumbnail(thumbnail.getBytes(), uploadPath, thumbnail.getContentType(),params);
            } catch (IOException e) {
                throw new ServiceException(e.getMessage());
            }
        }
        return oss;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }
        List<SysOss> list = baseMapper.selectBatchIds(ids);
        for (SysOss sysOss : list) {
            IOssStrategy storage = OssFactory.instance(sysOss.getService());
            storage.delete(sysOss.getUrl());
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<SysOss> selectSysOssList(SysOssBo sysOss) {
        return baseMapper.selectSysOssList(sysOss);
    }

    @Override
    public TableDataInfo<SysOssVo> selectSysOssByHandoverList(SysOssBo bo, PageQuery pageQuery) {
        Page<SysOssVo> result = baseMapper.selectSysOssByHandoverList(pageQuery.build(), bo);
        if(result == null || result.getRecords() == null || result.getRecords().size() == 0){
            LambdaQueryWrapper<SysOss> lqw = buildQueryWrapper(bo);
            result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        }
        return TableDataInfo.build(result);
    }

    @Override
    public Boolean deleteWithValidByUrl(String url) {
        LambdaQueryWrapper<SysOss> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysOss::getUrl,url);
        SysOssVo sysOss = baseMapper.selectVoOne(lqw);
        IOssStrategy storage = OssFactory.instance(sysOss.getService());
        storage.delete(sysOss.getUrl());
        return baseMapper.delete(lqw) > 0;
    }

    @Override
    public void updateOss(SysOss sysOss) {
        baseMapper.updateById(sysOss);
    }

    @Override
    public void addOss(SysOss sysOss) {
        baseMapper.insert(sysOss);
    }
}
